package com.example.deepschool.service.Likes;

import com.example.deepschool.Model.User;
import com.example.deepschool.exception.CustomException;
import com.example.deepschool.repositories.LikesRepository;
import com.example.deepschool.util.Redis;
import lombok.SneakyThrows;

public class LikesImpl implements Likes {

    private final LikesRepository likesRepository;

    public LikesImpl(LikesRepository likesRepository) {
        this.likesRepository = likesRepository;
    }

    @SneakyThrows
    @Override
    public Integer insert(Long discussionId, String UUID) {
        try {
            User user = User.fromJson(Redis.HGET(Redis.GET(UUID), "user"));
            com.example.deepschool.Model.Likes likes = new com.example.deepschool.Model.Likes();
            likes.setUserId(user.getId());
            likes.setDiscussionId(discussionId);
            return likesRepository.insert(likes);
        } catch (Exception e) {
            throw new CustomException(400, "点赞失败");
        }
    }

    @SneakyThrows
    @Override
    public Integer delete(Long discussionId, String UUID) {
        try {
            User user = User.fromJson(Redis.HGET(Redis.GET(UUID), "user"));
            com.example.deepschool.Model.Likes likes = new com.example.deepschool.Model.Likes();
            likes.setUserId(user.getId());
            likes.setDiscussionId(discussionId);
            return likesRepository.deleteByUserIdAndDiscussionId(likes);
        } catch (Exception e) {
            throw new CustomException(400, "取消点赞失败");
        }
    }

    @SneakyThrows
    @Override
    public Integer select(Long discussionId, String UUID) {
        try {
            User user = User.fromJson(Redis.HGET(Redis.GET(UUID), "user"));
            com.example.deepschool.Model.Likes likes = new com.example.deepschool.Model.Likes();
            likes.setUserId(user.getId());
            likes.setDiscussionId(discussionId);
            return likesRepository.selectByUserIdAndDiscussionId(likes);
        } catch (Exception e) {
            throw new CustomException(400, "查询点赞失败");
        }
    }
}
